package com.example.demo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/api/*", filterName = "loginFilter") //配置过滤请求等参数
public class CrosFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("【Filter】应用启动时初始化???");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("【Filter】新的请求每次都会执行请求时机？？？？");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //允许跨域的域
        response.setHeader("Access-Control-Allow-Origin", "*");
        //允许携带脚本程序
        response.setHeader("Access-Control-Allow-Credentials","true");
        //允许的跨域请求
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT,PATCH");
        //允许脚本访问返回的头
        response.setHeader("Access-Control-Expose-Headers", "true");
        //缓存此请求秒数
        response.setHeader("Access-Control-Max-Age", "3600");
        //自定义的头部
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("【Filter】服务器停止时销毁？？");
    }
}
